from datetime import datetime
import json
import re
from datetime import datetime as dt
from collections import deque

from flask import Flask, jsonify, session, current_app
from apscheduler.schedulers.background import BackgroundScheduler
import threading
import time
import requests
from flask_caching import logger

from app import db, User
from app.iot_mqtt.iot_funciton import ai_queue, set_device_properties
from app.models import Device, DeviceCommand

from app.routes.conversations import send_message, send_message_for_task


queue_lock = threading.Lock()
scheduler = BackgroundScheduler()

def extract_json_from_string(input_str):
    """
    从包含JSON的字符串中提取JSON对象

    参数:
        input_str (str): 包含JSON数据的字符串

    返回:
        dict: 提取的JSON对象
    """
    # 使用正则表达式匹配三个反引号之间的内容
    pattern = r'```json(.*?)```'
    match = re.search(pattern, input_str, re.DOTALL)

    if match:
        # 提取匹配到的JSON字符串并移除首尾空白
        json_str = match.group(1).strip()
        try:
            # 解析JSON字符串
            return json.loads(json_str)
        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {e}")
            return None
    else:
        print("未找到JSON数据")
        return None

def extract_command_from_text(ai_text):
    import json
    import re
    print("Raw input ai_text:", repr(ai_text))
    if not ai_text or not isinstance(ai_text, str):
        print("Error: ai_text is empty or not a string")
        return None
    command_str = ai_text.replace("False", "false").replace("True", "true")
    command_str = re.sub(r'^\s*|\s*$', '', command_str)
    command_str = re.sub(r'//.*?\n|/\*.*?\*/', '', command_str, flags=re.DOTALL)
    print("Processed command_str:", repr(command_str))
    try:
        command_json = json.loads(command_str)
        print("Parsed JSON:", json.dumps(command_json, indent=4, ensure_ascii=False))
        return command_json
    except json.JSONDecodeError as e:
        print("JSON Decode Error:", e)
        print("Failed string:", repr(command_str))
        return None


def analyze_data_task():
    from app import create_app
    app = create_app()
    with app.app_context():
        try:
            with queue_lock:
                current_messages = list(ai_queue)[-30:] if ai_queue else []
            if not current_messages:
                logger.info("没有新数据需要分析")
                return

            # 获取当前电价
            price_response = requests.get('http://localhost:5000/api/price/current')
            price_data = price_response.json()
            current_price = float(price_data.get('price', 0.604))
            current_period = price_data.get('period', '平段')

            current_data = {
                "user_id": 1,
                "role_id": 1,
                "message": {
                    "sensors": current_messages,
                    "price": {
                        "period": current_period,
                        "value": current_price
                    },
                    "time": datetime.now().isoformat()
                },
                "conversation_id": None
            }

            try:
                ai_response = send_message_for_task(current_data)
                logger.info(f"AI 原始响应: {ai_response}")
                command = extract_json_from_string(ai_response)
                if not command:
                    logger.warning("AI 响应无效，使用默认命令")
                    command = {
                        "paras": {
                            "gather": True,
                            "open_fan": True if current_period == "平段" and current_messages[-1].get("temperature",
                                                                                                      0) > 24 else False,
                            "open_water": False if current_messages[-1].get("humidity", 0) > 20 else True,
                            "open_led": True if current_messages[-1].get("light", 0) < 100 else False,
                            "led_red": 180 if current_period == "平段" else 100,
                            "led_blue": 180 if current_period == "平段" else 100,
                            "led_green": 180 if current_period == "平段" else 100,
                            "id": 1
                        },
                        "service_id": "Switch",
                        "command_name": "control"
                    }

                logger.info(f"最终命令: {json.dumps(command, indent=2, ensure_ascii=False)}")

                device_id = command['paras'].get('id')
                if device_id is None:
                    logger.error("命令中未提供设备 ID")
                    return

                device = Device.query.filter_by(id=device_id).first()
                if not device:
                    logger.error(f"设备 ID {device_id} 未找到")
                    return

                command_data = {k: v for k, v in command['paras'].items() if k != 'id'}
                command_type = 'set_rgb' if any(k in command_data for k in ['led_red', 'led_green', 'led_blue']) else \
                    list(command_data.keys())[0] if command_data else 'control'
                device_command = DeviceCommand(
                    device_id=device_id,
                    user_id=current_data['user_id'],
                    conversation_id=current_data['conversation_id'],
                    command_type=command_type,
                    command_data=command_data,
                    status='pending'
                )
                db.session.add(device_command)
                db.session.commit()
                logger.info(
                    f"已添加 DeviceCommand 记录: {device_command.id}, command_type: {command_type}, command_data: {command_data}")

                logger.info("命令已存储到数据库")

                # 执行 AI 命令
                success = set_device_properties(command)
                if success:
                    logger.info(f"AI 命令[{command['command_name']}]执行成功")
                else:
                    logger.error("AI 命令执行失败，可能设备离线")

                # 通过 /remote_control 验证
                # remote_response = requests.post(
                #     'http://localhost:5000/api/remote_control',
                #     json={'paras': command['paras']}
                # )
                # if remote_response.status_code == 200:
                #     logger.info(f"通过 /remote_control 执行 AI 命令成功: {remote_response.json()}")
                # else:
                #     logger.error(f"通过 /remote_control 执行 AI 命令失败: {remote_response.text}")

                # 计算成本
                cost_response = requests.post(
                    'http://localhost:5000/api/cost/calculate',
                    json={'command': command}
                )
                cost_data = cost_response.json()
                logger.info(f"成本对比: {cost_data}")

            except Exception as e:
                logger.error(f"AI处理流程异常: {str(e)}")
        except Exception as e:
            logger.error(f"任务全局异常: {str(e)}")
